import getIn from '../../../yali-sdk/utils/getIn';
import URL from '../../../yali-sdk/lib/URL';
import numberFormat from "../../numberFormat";
const liveroom = require('../../../yali-sdk/business/live/lib/liveroom.js');
const webim = require('../../../yali-sdk/business/live/lib/webim_wx.js');

let _interval;
let _this = null;

Component({
    properties: {
        roomid: {
            type: String,
            value: '',
            observer(newVal) {
                this.data.roomID = newVal;
            },
        },
        roomname: { type: String, value: 'undefined' },
        debug: { type: Boolean, value: false },
        template: { type: String, value: '1v1' },
        beauty: { type: Number, value: 5 },
        muted: { type: Boolean, value: false },
        pureaudio: { type: Boolean,
            value: false,
        },
        RoomEvent: { type: Function },
        anchor: { type: Object },
        total_live_zan: { type: Number },
        openWind:{type: Boolean}
    },

    data: {
        isCaster: true,
        menuItems: [],
        userName: '',
        userID: '',
        roomID: '',
        pusherContext: null,
        linkedPlayerContext: null,
        unload: 1,
        isInRoom: 0,
        unfold: false,
        mainPusherInfo: {
            url: '',
            aspect: '3:4',
            minBitrate: 0,
            maxBitrate: 0,
        },
        audience: {
            url: null,
            mixUrl: null,
            accelerateUrl: null,
            pusherName: '',
            pusherID: '',
            isLinked: false,
            aspect: '3:4',
            loading: false,
            objectFit: false,
        },
        linkPusherInfo: {
            url: '',
            loading: true,
            debug: true,
        },
        members: [],
        visualPlayers: [],
        requestLinking: false,
        dianZan: 1000,
        dianZanText: '1000',
    },
    methods: {
        toggleBeauty() {
            const self = this;
            const bty = self.data.beauty === 5 ? 0 : 5;
            self.setData({
                beauty: bty,
            }, () => {
                // // console.log(bty > 0 ? '开启美颜' : '关闭美颜');
            });
        },
        toggleMuted() {
            const self = this;
            self.setData({
                muted: !self.data.muted,
            }, () => {
            });
        },
        sendTextMsg(text) {
            const self = this;
            if (text.startsWith('>')) {
                switch (text) {
                    case '>debug': {
                        self.toggleDebug();
                        return;
                    }
                    default: break;
                }
            }
            liveroom.sendRoomTextMsg({
                data: { msg: text },
                success: () => {
                },
                fail: (e) => {
                    // // console.log('发送消息失败: ', e);
                    self.triggerEvent('RoomEvent', {
                        tag: 'error',
                        code: -9005,
                        detail: '发送消息失败',
                    });
                },
            });
        },
        switchCamera() {
            const self = this;
            self.data.pusherContext && self.data.pusherContext.switchCamera({});
        },
        respondJoinReq(agree, audience) {
            if (agree) {
                liveroom.acceptJoinPusher({
                    data: audience,
                });
            } else {
                liveroom.rejectJoinPusher({
                    data: audience,
                });
            }
        },

        setupLiveRoomListener() {
            const self = this;
            liveroom.setListener({
                onRoomClose: self.onRoomClose,
                onRecvRoomTextMsg: self.onRecvRoomTextMsg,
                onPusherQuit: self.onPusherQuit,
                onPusherJoin: self.onPusherJoin,
            });
        },

        start() {
            const self = this;
            // 请求CGI:get_push_url，异步获取到推流地址pushUrl
            liveroom.getPushURL({
                success(ret) {
                    const a = URL.parse(ret.pushURL);
                    const _t = a.pathname.split('/');
                    const pushUrlId = _t[_t.length - 1];// 推流地址标记
                    self.data.mainPusherInfo.url = ret.pushURL;
                    self.setData({
                        pushUrlId,
                        mainPusherInfo: self.data.mainPusherInfo,
                    }, () => {
                        self.setupLiveRoomListener();
                        self.data.pusherContext = wx.createLivePusherContext('pusher');
                        // 开始推流
                        self.data.pusherContext.start();
                    });
                },
                fail() {
                    self.triggerEvent('RoomEvent', {
                        tag: 'error',
                        code: -9002,
                        detail: '获取推流地址失败',
                    });
                },
            });
        },
        stop() {
            // // console.log('stop() called');
            const self = this;
            self.data.pusherContext && self.data.pusherContext.stop();
            const players = self.data.members;
            players && players.forEach((p) => { p.context && p.context.stop(); });
            // 重置信息
            self.setData({
                unload: 1,
                members: [{}],
                visualPlayer: [],
                pusherContext: null,
                linkedPlayerContext: null,
            });
            self.exit();
        },
        pause() {
            const self = this;
            self.data.pusherContext && self.data.pusherContext.pause();
        },
        resume() {
            wx.setKeepScreenOn({keepScreenOn: true,})
            const self = this;
            self.data.pusherContext && self.data.pusherContext.resume();
        },

        onPusherJoin(ret) {
            const self = _this;
            let temp = self.data.members.filter(e => e.userID);
            let pushers = ret.pushers;
            // 去掉自己
            let index = pushers.map(p => p.userID).indexOf(self.data.userID);
            if (index !== -1) pushers.splice(index, 1);
            // 去掉主播
            index = pushers.map(p => p.userID).indexOf(self.data.audience.pusherID);
            if (index !== -1) pushers.splice(index, 1);

            // // console.log(`%c===> ${pushers.length} 人加入Link`, 'color: red');
            pushers = pushers.map(p => ({
                userID: p.userID,
                userName: p.userName,
                accelerateURL: p.accelerateURL,
                context: null,
            }));

            temp = temp.concat(pushers);
            switch (self.data.template) {
                case '1v1': {
                    if (temp.length > 1) {
                        temp.splice(1, temp.length - 1);
                    } else if (temp.length < 1) {
                        temp.push({});
                    }
                    break;
                }
                default: break;
            }

            self.setData({
                members: temp,
            }, () => {
                temp.forEach((p) => {
                    if (p.context) return;
                    if (p.userID) p.context = wx.createLivePlayerContext(p.userID, self);
                });
                // // console.log('data.members: ', self.data.members);
            });
        },

        onPusherQuit(ret) {
            // // console.log('===> onPusherQuit() called: ', ret);
            const self = _this;
            const pushers = ret.pushers;
            const members = self.data.members;
            for (const p of pushers) {
                for (const i in members) {
                    if (p.userID === members[i].userID) {
                        members[i].context && members[i].context.stop();
                        members.splice(i, 1);
                        members.push({});
                        break;
                    }
                }
            }
            self.setData({
                members,
            }, () => {
                // console.log('members after onPusherQuit: ', self.data.members);
            });
        },
        create() {
            const self = this;
            liveroom.createRoom({
                data: {
                    roomInfo: self.data.roomname,
                    pushURL: self.data.mainPusherInfo.url,
                },
                success(ret) {
                    self.setData({
                        roomID: ret.roomID,
                    });
                    self.triggerEvent('RoomEvent', {
                        tag: 'created',
                        code: 0,
                        detail: '创建房间成功',
                        roomID: ret.roomID,
                        pushUrlId: self.data.pushUrlId,
                    });
                },
                fail(ret) {
                    // console.error('创建房间失败', ret);
                    if (!self.data.unload) {
                        self.data.pusherContext.stop();
                    }
                    self.triggerEvent('RoomEvent', {
                        tag: 'error',
                        code: -9001,
                        detail: '创建房间失败',
                    });
                },
            });
        },

        exit() {
            // console.log('exit() called');
            liveroom.exitRoom({});
        },

        onPlay(ret) {
            const self = this;
            // console.error('拉流情况：', ret.detail.code);
            switch (ret.detail.code) {
                case -2301: {
                    // 多次拉流失败
                    // console.error('多次拉流失败');
                    self.triggerEvent('RoomEvent', {
                        tag: 'error',
                        code: ret.detail.code,
                        detail: '多次拉流失败',
                    });
                    break;
                }
                default: break;
            }
        },

        playMixedUrl() {
            // console.log('==> playMixedUrl');
            const self = _this;
            const players = [{
                debug: false,
                mute: false,
                url: self.data.audience.mixUrl,
                mode: 'live',
                maxCache: 5,
                minCache: 1,
                loading: false,
                objectFit: 'contain',
                userName: self.data.audience.pusherName,
            }];
            return new Promise((resolve) => {
                self.setData({
                    visualPlayers: players,
                }, () => {
                    resolve();
                });
            });
        },

        playAccelerateUrl() {
            const self = _this;
            const players = [{
                debug: false,
                mute: false,
                url: self.data.audience.accelerateUrl,
                mode: 'RTC',
                maxCache: 0.3,
                minCache: 0.1,
                loading: false,
                objectFit: 'fillCrop',
                userName: self.data.audience.pusherName,
            }];
            return new Promise((resolve) => {
                self.setData({
                    visualPlayers: players,
                }, () => {
                    resolve();
                });
            });
        },
        stopPlayUrl() {
            const self = _this;
            return new Promise((resolve) => {
                self.setData({
                    visualPlayers: [],
                }, () => {
                    resolve();
                });
            });
        },

        getPushUrl() {
            return new Promise((resolve, reject) => {
                liveroom.getPushURL({
                    success(ret) {
                        // console.log('getPushURL() 成功，', ret);
                        resolve(ret.pushURL);
                    },
                    fail(e) {
                        // console.log('getPushUrl() 获取推流地址失败: ', e);
                        reject(e);
                    },
                });
            });
        },
        startLinkPush(url) {
            // console.info('startLinkPush() called');
            const self = _this;
            return new Promise((resolve) => {
                self.data.linkPusherInfo.url = url;
                self.data.members.splice(0, 1);
                self.setData({
                    members: self.data.members,
                    linkPusherInfo: self.data.linkPusherInfo,
                }, () => {
                    self.data.pusherContext = wx.createLivePusherContext('audience_pusher');
                    // console.log('startLinkPush.创建 pusherContext：', self.data.pusherContext);
                    self.data.pusherContext.start();
                    resolve();
                });
            });
        },
        link() {
            const self = this;
            // 停止mix流播放 --> 播放 accelerate流 --> 获取推流连接开始推流 --> onLinkPush 成功后 jionPusher
            Promise.resolve()
                .then(self.stopPlayer)
                .then(self.playAccelerateUrl)
                .then(self.getPushUrl)
                .then(self.startLinkPush)
                .then(() => new Promise((resolve) => {
                    resolve();
                }))
                .catch(() => {
                    // console.log('过程出错： 停止mix流播放 --> 播放 accelerate流 --> 获取推流连接开始推流 --> onLinkPush 成功后 jionPusher: ', e);
                    self.triggerEvent('RoomEvent', {
                        tag: 'error',
                        code: -1,
                        detail: '连麦过程发生错误',
                    });
                });
        },
        kickoutSubPusher(e) {
            const self = _this;
            const userID = e.currentTarget.dataset.userid;
            liveroom.kickoutSubPusher({
                data: { userID },
                success: () => {
                    const members = self.data.members;
                    const index = members.map(m => m.userID).indexOf(userID);
                    if (index !== -1) {
                        // members[index].context && members[index].context.stop();
                        members.splice(index, 1);
                        members.push({});
                    }
                    self.setData({
                        members,
                    });
                },
                fail: () => {
                },
            });
            // todo
        },
        resetToAudience() {
            // console.log('resetToAudience() called');
            const self = _this;
            Promise.resolve()
                .then(() =>   // 停止推流
                    // console.log('停止推流');
                     new Promise((resolve) => {
                        // console.log('停止推流');
                         self.data.pusherContext && self.data.pusherContext.stop();
                         self.data.linkPusherInfo.url = null;
                         self.setData({
                             pusherContext: null,
                             linkPusherInfo: self.data.linkPusherInfo,
                         }, () => resolve());
                     }))
                .then(() =>  // 清理member players
                    // console.log('清理 member players');
                     new Promise((resolve) => {
                         let pushers = self.data.members;
                         pushers && pushers.forEach((p) => { p.context && p.context.stop(); });
                         pushers = self.data.template === '1v1' ? [{}] : [{}, {}, {}];
                         self.setData({ members: pushers }, () => resolve());
                     }))
                .then(self.stopPlayUrl) // 停止播放 acelerate 流
                .then(self.playMixedUrl) // 播放mixed 流
                .then(() => new Promise((resolve) => {
                    self.triggerEvent('RoomEvent', {
                        tag: 'LinkOut',
                        code: 0,
                        detail: '连麦断开',
                    });
                    resolve();
                }))
                .catch((e) => {
                    // console.error('resetToAudience 流程出现错误：', e);
                });
        },

        onPushEvent(code) {
            const self = this;
            switch (code) {
                case -1301: {
                    // // console.log('打开摄像头失败: ', ret.detail.code);
                    self.triggerEvent('RoomEvent', {
                        tag: 'error',
                        code: -1301,
                        detail: '打开摄像头失败',
                    });
                    break;
                }
                case -1302: {
                    // // console.log('打开麦克风失败: ', ret.detail.code);
                    self.triggerEvent('RoomEvent', {
                        tag: 'error',
                        code: -1302,
                        detail: '打开麦克风失败',
                    });
                    break;
                }
                case -1307: {
                    // 推流连接断开就做退房操作
                    self.exit();
                    self.triggerEvent('RoomEvent', {
                        tag: 'error',
                        code: -1307,
                        detail: '推流连接断开',
                    });
                    break;
                }
                default: break;
            }
        },
        onLinkPush(ret) {
            const self = this;
            switch (ret.detail.code) {
                case 1002: {
                    break;
                }
                case 5000: {
                    // 收到5000就退房
                    self.exit();
                    self.data.exit = 5000;
                    self.triggerEvent('RoomEvent', {
                        tag: 'error',
                        code: 5000,
                        detail: 'link push error!(5000)',
                    });
                    break;
                }
                default: {
                    self.onPushEvent(ret.detail.code);
                    break;
                }
            }
        },
        onMainPush(ret) {
            const self = this;
            switch (ret.detail.code) {
                case 1005: {
                    // console.log('推流动态分辨率改变： ', ret);
                    break;
                }
                case 1002: {
                    // console.log('推流成功：', ret.detail.code);
                    if (!self.data.isInRoom) {
                        self.setData({ isInRoom: 1 });
                        // 4.推流成功，请求CGI:create_room，获取roomID、roomSig
                        self.create();
                    }
                    break;
                }

                case 5000: {
                    // 收到5000就退房
                    self.exit();
                    self.data.exit = 5000;
                    self.triggerEvent('RoomEvent', {
                        tag: 'error',
                        code: 5000,
                        detail: 'main push error!(5000)',
                    });
                    break;
                }
                default: {
                    self.onPushEvent(ret.detail.code);
                    break;
                }
            }
        },
        onMainError() {
            _this.triggerEvent('RoomEvent', {
                tag: 'error',
                code: -1,
                detail: '播放错误',
            });
        },

        onRoomClose() {
            _this.triggerEvent('RoomEvent', { tag: 'roomClosed', code: -9006, detail: '房间已经解散了' });
        },

        onRecvRoomTextMsg(ret) {
            _this.triggerEvent('RoomEvent', {
                tag: 'recvTextMsg',
                code: 0,
                detail: ret,
            });
        },
        loadNumber: () => {
            _this.data.roomID && _this.data.roomID.length > 0 && webim.getGroupInfo({
                GroupIdList: [_this.data.roomID],
                GroupBaseInfoFilter: [  // 如果基础信息字段，请在此数组中添加
                    'MemberNum',
                ],
            }, (res) => {
                const onlineMemberNum = numberFormat(getIn(res, ['GroupInfo', 0, 'MemberNum'])) || '';
                _this.setData({
                    onlineMemberNum,
                });
            });
        },
    },

    attached() {
        _interval = setInterval(this.loadNumber, 10000);
        // 保持屏幕常亮
        wx.setKeepScreenOn({
            keepScreenOn: true,
        });

        const self = this;
        _this = this;
        const { userID, userName } = liveroom.getAccountInfo();

        self.setData({
            userID,
            userName,
            unload: 0,
            members: self.data.template === '1v1' ? [{}] : [{}, {}, {}],
        });
        // // console.log('data: ', self.data);
    },

    detached() {
        _interval && clearInterval(_interval);
        const self = this;
        _this = null;
        self.stop();
    },

});
